﻿using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading ;
using System.Collections.Generic;

namespace Server
{
    class Program
    {
        public static int port = 13000;
        public static  List<Client> lst = new List<Client>();
        public static void BCast(Socket mySocket, byte[] barr)
        {
            foreach (Client p in lst)
            {
                IPEndPoint ipEndPoint = p.ThisSocket.RemoteEndPoint as IPEndPoint;
                ipEndPoint.Port = 13001;
                Socket sendTo = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                sendTo.Connect(ipEndPoint);
                sendTo.Send(barr);
                logWriter(barr);
            }
        }
        public static void logWriter(byte[] msg)
        {
            using (StreamWriter sw = File.AppendText(@"log.txt"))
            {
                string str = Encoding.Default.GetString(msg);               
                sw.WriteLine(str);                
                sw.Close();
            }
        }
       public class Client
        {
            public string NickName = null;
            public Socket ThisSocket = null;
            string msg;
            public Client(Socket RecSoc) 
            {
                ThisSocket = RecSoc;
                Thread thr = new Thread(connect);
                thr.Start();                
            }
            public void connect()
            {
                while (true)
                {                    
                    byte[] bytes = new byte[256];
                    ThisSocket.Receive(bytes);
                    msg = Encoding.Default.GetString(bytes);
                    string[] split = msg.Split(':');
                    NickName = split[0];
                    Console.WriteLine(msg);
                    Program.BCast(ThisSocket, bytes);
                }
            }
        }
        static void Main(string[] args)
        {
            TcpListener serverLi = new TcpListener(IPAddress.Parse("127.0.0.1"), port);
            serverLi.Start();
            Console.Write("Waiting for a connection... ");
            Client cl = null;
            while(true) 
            {
                 cl = new Client(serverLi.AcceptSocket());
                 lst.Add(cl);                
             }
            foreach (Client p in lst) 
            {
                p.ThisSocket.Close();
            }
            serverLi.Stop();
            Console.ReadKey();
    }
}

       
}


